<?php
/**
 * Created by PhpStorm.
 * User: xaq
 * Date: 2017/5/15
 * Time: 16:31
 */

namespace app\index\controller;


use think\Controller;
use think\Request;
use think\Image;
use app\index\model\Image as ImageModel;

class Upload extends Controller
{
    //文件上传表单
    public function index(){
        return $this->fetch();
    }
    //文件上传提交
    public function up(Request $request){
        //获取表单上传文件
        $file = $request->file('file');
        if(empty($file)){
            $this->error('请选择上传文件');
        }
        //移动到框架应用根目录/public/uploads目录下
        $info = $file->move(ROOT_PATH.'public'.DS.'uploads');
        if($info) {
            $this->success('文件上传成功'.$info->getRealPath());
        }else {
            //上传失败获取错误信息
            $this->error($file->getError());
        }
    }

    //图片上传处理
    public function picture(Request $request){
        $file = $request->file('image');
        if(true !== $this->validate(['image' => $file],['image' => 'require'])) {
            $this->error('请选择图像文件');
        }else{
            //读取图片
            $image = Image::open($file);
            //图片处理
            switch($request->param('type')){
                case 1: // 图片裁剪
                    $image->crop(300,300);
                    break;
                case 2: //缩略图
                    $image->thumb('150',150,Image::THUMB_CENTER);
                    break;
                case 3: // 垂直翻转
                    $image->flip();
                    break;
                case 4: // 水平翻转
                    $image->flip(Image::FLIP_Y);
                    break;
                case 5: // 图片翻转
                    $image->rotate();
                    break;
                case 6: // 图片水印x
                    $image->water('./logo.png',Image::WATER_SOUTHEAST,50);  //将logo图片放到public目录下
                    break;
                case 7: //文字水印
                    $image->text('ThinkPHP',VENDOR_PATH.'topthink/think-captcha/assets/ttfs/1.ttf', 20, '#ffffff');
                    break;
            }
            // 保存图片（以当前时间戳）
            $saveName = $request->time().'.png';
            $result = $image->save(ROOT_PATH.'public/uploads/'.$saveName);
//            if($result) {
//                $this->success('图片处理完毕...','/uploads/'.$saveName,1);
//                //$this->success('图片处理完毕');
//            }else {
//                $this->error('图片上传失败');
//            }
            //将图片路径添加到数据库
            $pathUrl = ROOT_PATH.'public/uploads/'.$saveName;
            print_r($pathUrl);
            $data = [
                'url' =>$pathUrl ,
            ];
            $saveImage = ImageModel::create($data);
            return json($saveImage);
        }
     }

}